<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    :fit="true"
  >
    <el-table-column
      label="序号"
      type="index"
      :index="indexMethod"
      align="center"
    />
    <el-table-column
      v-for="(item, index) of tableColumns"
      :key="index"
      :prop="tableColumns[index].key"
      :label="tableColumns[index].name"
      show-overflow-tooltip
      align="center"
    />
  </el-table>
</template>

<script>
import { queryEnterprise } from '@/api/enterprise'
import { queryBase } from '@/api/base'

export default {
  props: {
    role: {
      type: Number,
      required: true
    },
    account: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      tableData: [],
      tableColumns: []
    }
  },
  watch: {
    role: {
      handler(newValue) {
        if (newValue === 1) {
          this.tableColumns = [{
            name: '基地名称',
            key: 'siteName'
          }, {
            name: '所属企业',
            key: 'entName'
          }]
        } else if (newValue === 4) {
          this.tableColumns = [{
            name: '企业名称',
            key: 'entName'
          }, {
            name: '企业地址',
            key: 'address'
          }, {
            name: '详细地址',
            key: 'location'
          }]
        }
      },
      immediate: true
    }
  },
  created() {
    this.fetchData()
    console.log(this.role)
  },
  methods: {
    fetchData() {
      if (this.role === 4) {
        this.getEnt()
      } else if (this.role === 1) {
        this.getSite()
      }
    },
    async getEnt() {
      const res = await queryEnterprise({
        account: this.account,
        page: -1,
        limit: -1
      }) // 请求企业数据
      const ents = res.enterprise // 获取企业数据
      ents.map(item => {
        item.address = `${item.province} ${item.city} ${item.county}`
      }) // 处理企业数据
      this.tableData = ents
    },
    async getSite() {
      const res = await queryBase({
        account: this.account
      }) // 请求基地数据
      const ents = res.enterprise // 获取企业数据
      const sites = res.plantation // 获取基地数据
      sites.map((item, index) => { // 处理基地数据
        item.entName = ents[index].entName
      })
      this.tableData = sites
    },
    indexMethod(index) {
      return index + 1
    }
  }
}
</script>
